package cn.bjc.controller;

import cn.bjc.domain.Product;
import cn.bjc.domain.Store;
import cn.bjc.feign.StoreFeignService;
import cn.bjc.service.IProductService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/product")
@RefreshScope // 动态刷新配置注解
public class ProductController {

    @Value("${test.name}")
    private String name;
    
    @Autowired
    private IProductService productService;
    
    @Autowired
    private StoreFeignService storeFeignService;
    
    @GetMapping("/getById/{id}")
    @SentinelResource(value = "product-service-getById",fallback = "fallbackProductMethod")
    public Store getById(@PathVariable("id") Long id){
        System.out.println(name);
        return storeFeignService.getById(id);
    }
    
    @PostMapping("/add")
    public Map<String,Object> add(@RequestBody Product product){
        try {
            //1.商品表添加数据
            productService.add(product);
            
            //2.新建一个store
            Store store = new Store();
            
            //3.商品表添加后得到自增长主键
            //主键id为store表对应的product_id
            store.setProduct_id(product.getId());
            store.setNumber(product.getNumber());
            
            //4.调用feign接口将store传给库存服务进行添加
            storeFeignService.add(store);
            
            //添加成功返回成功数据
            HashMap<String,Object> map=new HashMap<>();
            map.put("success",true);
            map.put("message","数据添加成功");
            return map;
            
        } catch (Exception e) {
            e.printStackTrace();
            
            //添加失败返回失败数据
            HashMap<String,Object> exceptionMap=new HashMap<>();
            exceptionMap.put("success",false);
            exceptionMap.put("message","服务器异常");
            return exceptionMap;
        }
    }
    
    //熔断的本类
    public Store fallbackProductMethod(@PathVariable("id") Long id, Throwable e){
        e.printStackTrace();
        return new Store(-11L, null, null);
    }
    
}
